<template>
    <div class="wave_content" ref="container" v-loading="loadingNum != 0" element-loading-background="rgba(0, 0, 0, 0.3)">
        <el-select v-model="tagsSelected" collapse-tags multiple placeholder="请选择特征值">
            <el-option v-for="item in tags" :key="item.id" :label="item.value" :value="item" />
        </el-select>
        <div class="maps" ref="box" @contextmenu.prevent="contextMenu($event)"></div>
        <vue-context-menu v-if="contextMenuData" :contextMenuData="contextMenuData" @downloadData="downloadData" @selectTime="selectTime" @doubleLine="doubleLine" @handleMean="handleMean" @batchData="batchData" />

        <export-excel :sensorInfo="sensorInfo" ref="exportExcel" />
        <mean-value :list="list" ref="meanValue" />
        <bulk-download ref="bulkDownVue" />
    </div>
</template>

<script>
import { eigenvalueTagsApi, eigenvalueSensorGetlistApi } from '@/requset/api'
import { options } from './config.js'
import * as echarts from 'echarts'
import exportExcel from '@/components/exportExcel'
import meanValue from './meanValue.vue'
import bulkDownload from '@/components/common/bulkDownload'
export default {
    data() {
        return {
            tags: [],
            tagsSelected: [],
            options: null, //图表配置
            list: {},
            wave_time: null,
            loadingNum: 0,
            loading: null,
        }
    },
    components: { exportExcel, meanValue, bulkDownload },
    computed: {},
    props: {
        sensorInfo: {
            type: Object,
            default() {
                return {}
            },
        },
        date_time: {
            type: Array,
            default() {
                return []
            },
        },
        active: {
            type: Boolean,
            default() {
                return false
            },
        },
        contextMenuData: {
            type: Object,
            default() {
                return null
            },
        },
        eigname: {
            type: String,
            default() {
                return ''
            },
        },
        warnState: {
            type: Boolean,
            default() {
                return false
            },
        },
    },
    watch: {
        active: {
            handler(newVal) {
                if (newVal) {
                    if (this.sensorInfo.id) this.getTags(this.sensorInfo.id, this.sensorInfo.direction)
                }
            },
        },
        sensorInfo: {
            handler(newVal, oldVal) {
                if (this.active && newVal.id) {
                    if (oldVal === undefined ? true : oldVal.sensor_type === newVal.sensor_type) {
                        // 测点类型未变化，仅绘制图形
                        if (newVal.single == 1) {
                            this.getTags(newVal.id, newVal.direction).then(() => {
                                for (let i = 0; i < this.tagsSelected.length; i++) {
                                    if (i < this.tagsSelected.length - 1) this.getList(this.tagsSelected[i])
                                    else this.getList(this.tagsSelected[i]).then(() => this.draw(this.list))
                                }
                            })
                        } else {
                            for (let i = 0; i < this.tagsSelected.length; i++) {
                                if (i < this.tagsSelected.length - 1) this.getList(this.tagsSelected[i])
                                else this.getList(this.tagsSelected[i]).then(() => this.draw(this.list))
                            }
                        }
                    } else {
                        this.getTags(newVal.id, newVal.direction)
                            .then(() =>
                                Promise.all(
                                    this.tagsSelected.map((tag) => {
                                        this.getList(tag)
                                    }),
                                ),
                            )
                            .then(() => this.draw(this.list))
                    }
                }
            },
            deep: true,
            immediate: true,
        },
        date_time: {
            handler(newVal) {
                if (this.active) {
                    var len = this.tagsSelected.length
                    for (let i = 0; i < len; i++) {
                        if (i < len - 1) {
                            this.getList(this.tagsSelected[i])
                        } else {
                            this.getList(this.tagsSelected[i]).then(() => {
                                this.draw(this.list)
                            })
                        }
                    }
                }
            },
        },
        tagsSelected: {
            handler(newVal, oldVal) {
                const addedElements = newVal.filter((item) => !oldVal.includes(item)) // 获取新增的元素
                if (newVal.length === 0) {
                    this.clearChart()
                    return
                }
                if (addedElements.length > 0) {
                    const firstAddedElement = addedElements[0] // 只关注第一个新增的元素

                    this.getList(firstAddedElement).then(() => this.draw(this.list))
                }
            },
        },
    },
    methods: {
        getTags(id, direction) {
            // 获取可选择标签
            if (!id) return
            return eigenvalueTagsApi(id).then((res) => {
                if (res.data.code == 0) {
                    let list = res.data.data
                    this.$emit('sendTags', list)
                    this.setDefaultTag(list, direction)
                    this.tags = list
                }
            })
        },
        setDefaultTag(list, direction) {
            if (list.length != 0) {
                let a = 'Speed'
                let b = ''
                if (direction == 'A') b = 'x'
                else if (direction == 'H') b = 'y'
                else if (direction == 'V') b = 'z'
                let s = list.find((item) => item.nickname === b + a)
                if (s) this.tagsSelected = [s]
                else this.tagsSelected = [list[0]]
                if (this.eigname != '') {
                    let s = list.find((item) => item.nickname == this.eigname)
                    if (s) this.tagsSelected = [s]
                }
            }
        },
        getList(tagsSelected) {
            function dilution(data) {
                let saveCount = 6000
                const compressedData = []
                const ratio = data.length / saveCount // 计算压缩比例
                if (data.length <= saveCount) {
                    return data
                }
                for (let i = 0; i < saveCount; i++) {
                    const index = Math.floor(i * ratio) // 根据比例计算新数组中对应的索引位置
                    compressedData.push(data[index])
                }
                return compressedData
            }
            let feature_key = tagsSelected.nickname
            let obj = {
                id: this.sensorInfo.id,
                startTime: this.date_time[0].getTime(),
                endTime: this.date_time[1].getTime(),
                feature_key,
            }
            this.loadingNum++
            return eigenvalueSensorGetlistApi(obj)
                .then((res) => {
                    if (res.data.code == 0) {
                        let arr = res.data.data
                        if (arr.length == 0) {
                            this.list[feature_key] = []
                            return
                        }
                        if (feature_key.includes('Displacement')) {
                            // 遍历数组并判断value值的最大值
                            var maxVal = 0
                            for (var i = 0; i < arr.length; i++) {
                                var item = arr[i]
                                if (parseFloat(item.value) > maxVal) {
                                    maxVal = parseFloat(item.value)
                                }
                            }
                            // 判断最大值是否小于5并输出结果
                            if (maxVal < 5) {
                                this.options.yAxis.max = maxVal * 5
                            }
                        } else {
                            this.options.yAxis.max = null
                        }
                        this.list[feature_key] = dilution(arr)
                    } else {
                        this.clearChart()
                        this.$message.info(res.data.msg)
                        this.list[feature_key] = []
                    }
                })
                .catch((err) => {
                    this.clearChart()
                    this.$message.info('请求超时')
                    this.list[feature_key] = []
                })
                .finally(() => this.loadingNum--)
        },
        draw(list) {
            let ref = this.$refs.box
            var myChart = echarts.init(ref)
            let tagsSelected = this.tagsSelected

            let legendData = []
            let seriesData = []
            tagsSelected.forEach((e1) => {
                var arr = []
                legendData.push(e1.value + ' ' + e1.unit)
                let Arr = list[e1.nickname]
                if (Arr)
                    Arr.forEach((e2) => {
                        arr.push([e2.time, e2.value])
                    })
                let obj = {
                    name: e1.value + ' ' + e1.unit,
                    data: arr,
                    type: 'line',
                    symbol: 'circle',
                    smooth: false,
                    symbolSize: 2,
                    connectNulls: false,
                    hoverAnimation: false,
                }
                seriesData.push(obj)
            })
            this.options.legend.data = legendData
            this.options.series = seriesData
            this.options.xAxis.type = 'time'
            this.options.yAxis.name = '特征值'
            this.options.tooltip.formatter = (params) => {
                this.wave_time = params[0].data[0]
                var res = '时间：  ' + params[0].data[0] + '<br/>'
                for (var i = 0; i < params.length; i++) {
                    res += params[i].seriesName + '     ' + params[i].data[1] + '<br/>'
                }
                return res
            }

            this.clearChart()
            myChart.setOption(this.options)
            const chartObserver = new ResizeObserver(() => {
                myChart.resize()
            })
            chartObserver.observe(ref)
            window.addEventListener('resize', () => {
                myChart.resize()
            })
        },
        clearChart() {
            let ref = this.$refs.box
            let myChart = echarts.init(ref)
            if (myChart) myChart.clear()
            ref.removeAttribute('_echarts_instance_')
        },
        contextMenu(e) {
            //右击展示菜单
            let x = e.clientX
            let y = e.clientY
            this.contextMenuData.axis = { x, y }
        },
        downloadData() {
            //  1表示 导出特征值数据 2 表示导出频谱 或 包络谱数据
            let { tagsSelected, list } = this
            this.$refs.exportExcel.downloadData(1, { tagsSelected, list })
        },
        selectTime() {
            if (this.wave_time) {
                this.$emit('recentTime', this.wave_time)
            }
        },
        //均值
        handleMean() {
            let { tagsSelected, list } = this
            this.$refs.meanValue.doOpen(tagsSelected, list)
        },
        //批量导出
        batchData() {
            this.$refs.bulkDownVue.doOpen(this.tags)
        },
    },
    created() {
        this.options = options
    },
}
</script>

<style scoped lang="less">
.wave_content {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;

    .el-select {
        width: 190px;
        margin-right: 4px;
    }

    .maps {
        width: 100%;
        height: 94%;
        // overflow-x: auto;
        position: relative;

        .echarts_noData {
            text-align: center;
            margin-top: 10%;

            img {
                width: 320px;
            }

            div {
                margin-top: 10px;
                color: #b2e3ff;
                font-size: 18px;
                font-weight: 600;
            }
        }
    }
}
</style>
